import { Component, OnInit } from '@angular/core';
import { NavParams,ViewController } from 'ionic-angular';
import { IndexService } from './index.service';

@Component({
  templateUrl: 'index.component.html',
  providers: [ IndexService ]
})
export class IndexPage implements OnInit {
  materialID:number;
  indexGroups:Array<any> = [];
  materialIndexs:string;
  selectedArr:Array<any> = [];

  constructor(
    private navParams: NavParams,
    private IndexService: IndexService,
    public viewCtrl: ViewController) {
    this.materialID = this.navParams.get('materialID');
    this.selectedArr = this.navParams.get('materialIndexIds') == undefined? [] :  this.navParams.get('materialIndexIds');
    this.materialIndexs = this.navParams.get('materialIndexs') == undefined? [] : this.navParams.get('materialIndexs');
  }

  ngOnInit() {
    this.IndexService.listMaterialIndex(this.materialID).subscribe(data => {
      this.indexGroups = data['indexGroups'];
      if(this.materialIndexs != null){
        this.indexGroups.forEach(ele => {
          this.selectedArr.forEach(i =>{
            if(i.idxGroupID == ele.idxGroupID){
              ele.indexs.forEach(e => {
                if(i.idxValue == e.idxValue){
                  ele['defaultVal'] = e.idxValue;
                }
              });
            }
          });
       });
      }
    });
  }

  /** 关闭窗口 */
  dismiss() {
    let data = { 'materialIndexs': this.materialIndexs,'materialIndexIds':this.selectedArr};
    this.viewCtrl.dismiss(data);
  }

  /** 提交申请 */
  submit(){
    /**
     * TODO 指标选择是否齐全校验
     */
    let data = { 'materialIndexs': this.materialIndexs,'materialIndexIds':this.selectedArr};
    this.viewCtrl.dismiss(data);
  }

  /**属性选中 */
  checkIndex(idxGroupID, idxValue,idxID) {
    var hasIndex =false;
    this.selectedArr.forEach(j =>{
      if(j.idxGroupID == idxGroupID){
        hasIndex = true;
        j['idxValue'] = idxValue;
      }
    });
    if(!hasIndex){
      this.selectedArr.push({idxGroupID,idxValue});
    }

    this.indexGroups.forEach(i => {
      if (i.idxGroupID == idxGroupID) {
        i['defaultVal'] = idxValue;
      }
    });
    //页面显示
    this.materialIndexs ="";
    this.selectedArr.forEach(j =>{
      this.materialIndexs += " "+j['idxValue'];
    });
  }
}
